#include "rungekutta.h"
#include<qstring.h>
#include<vector.h>
#include<f.h>
RungeKutta::RungeKutta(int orden, QString dx, QString dy, double x0, double y0, double t0, double tf, double n)
{
    this->x0=x0;
    this->y0=y0;
    this->t0=t0;
    this->tf=tf;
    this->dx=dx;
    this->dy=dy;
    this->n=n;
    this->orden=orden;
    this->puntos=new Lista();
    calcular();
}

void RungeKutta::calcular()
{
    //this->puntos->elementos->clear();
    if(orden==2)
        calcularPuntosRK2();
    if(orden==4)
        calcularPuntosRK4();
    puntos->elementos->append(Vector(NULL,NULL,NULL));
}

void RungeKutta::calcularPuntosRK2()
{
    double h = (tf-t0)/n;
    //this->puntos->elementos->clear();
    F f(dx, dy);
    Vector F1;
    Vector F2;
    Vector Xn(x0, y0,t0);
    puntos->append(Xn);
    Vector Xn1;
    for(double t= t0; t<tf; t+=h)
    {
        F1 =f.evaluar(t, Xn)*  h ;
        F2 =f.evaluar(t+h, Xn+F1)*  h ;
        Xn1 = Xn + ( (F1 + F2)*1/2);
        Xn1.t=t+h;
        puntos->append(Xn1);
        Xn=Xn1;
    }
}

void RungeKutta::calcularPuntosRK4()
{
    double h = (tf-t0)/n;
    F f(dx, dy);
    Vector F1;
    Vector F2;
    Vector F3;
    Vector F4;
    Vector Xn(x0, y0,t0);
    puntos->append(Xn);
    Vector Xn1;
    for(double t= t0; t<tf; t+=h)
    {
        F1 =f.evaluar(t, Xn)*  h ;
        F2 =f.evaluar(t+h*0.5, Xn+F1*0.5)*  h ;
        F3 =f.evaluar(t+h*0.5, Xn+F2*0.5)*  h ;
        F4 =f.evaluar(t+h, Xn+F3)*  h ;
        Xn1 = Xn + (F1+F2*2+F3*2+F4)*(1/6);
        Xn1.t=t+h;
        puntos->append(Xn1);
        Xn=Xn1;
    }
}

RungeKutta::~RungeKutta()
{
    delete puntos;
}

